package com.shopmall.controller;


import com.shopmall.pojo.AdminRecord;
import com.shopmall.pojo.Excel;
import com.shopmall.pojo.Goods;
import com.shopmall.pojo.GoodsInList;
import com.shopmall.service.AdminRecordServiceImpl;
import com.shopmall.service.GoodsInListServiceImpl;
import com.shopmall.service.GoodsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@RestController
public class ExcelController {
    @Autowired
    private static  final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private GoodsServiceImpl goodsService;

    @Autowired
    private GoodsInListServiceImpl goodsInListService;

    @Autowired
    private AdminRecordServiceImpl adminRecordService;

    /*
    @RequestMapping(method = RequestMethod.POST)
    @RequiresPermissions(value = {Permission.FILE_UPLOAD})
    public Object upload(@RequestPart("file") MultipartFile multipartFile) {

        try {
            FileInfo fileInfo = fileService.upload(multipartFile);
            return Rets.success(fileInfo);
        } catch (Exception e) {
            logger.error("上传文件异常",e);
            return Rets.failure("上传文件失败");
        }
    }


    @RequestMapping(value="download",method = RequestMethod.GET)
    public void download(@RequestParam("idFile") Long idFile,
                           @RequestParam(value = "fileName",required = false) String fileName){
        FileInfo fileInfo = fileService.get(idFile);
        fileName = StringUtil.isEmpty(fileName)? fileInfo.getOriginalFileName():fileName;
        HttpServletResponse response = HttpUtil.getResponse();
        response.setContentType("application/x-download");
        try {
            fileName = new String(fileName.getBytes(), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;

        OutputStream os = null;
        try {
            File file = new File(fileInfo.getAblatePath());
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
            }

        } catch (Exception e) {
            logger.error("download error",e);
        }finally {
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                logger.error("close inputstream error", e);
            }
        }

    }

     */

    @RequestMapping("/goods/excelDownload")
//    @RequiresPermissions(value = {Permission.FILE})
    public void goods_download(HttpServletResponse response, HttpServletRequest request) {
        //这里是笔者实际业务需求中需要得到时间间隔。可忽略
//        String start = request.getParameter("start");
//        String end = request.getParameter("end");
//        System.out.println("打印的起始日期为：" + start + "，打印的结束日期为：" + end);
        //得到所有要导出的数据
        List<Goods> goodsList = goodsService.queryGoodsList();
//        List<Excel> list1 = new ArrayList<Excel>();
//
//        for (Goods goods : goodsList) {
//            Excel excel = new Excel();
//            excel.setId(goods.getUserID());
//            excel.setCreated_time(goods.getCreateTime());
//            excel.setMobile(goods.getMobile());
//            excel.setRemark(goods.getRemark());
//            excel.setStatus(goods.getStatus());
//            excel.setUserid(goods.getUserID());
//            list1.add(excel);
//        }
        //定义导出的excel名字
        String excelName = "商品详情表";
        //获取需要转出的excel表头的map字段
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
        fieldMap.put("goods_id", "商品编号");
        fieldMap.put("name", "商品名称");
        fieldMap.put("type", "商品类型");
        fieldMap.put("num", "数量");
        fieldMap.put("norm", "商品规格");
        fieldMap.put("price_in", "商品进价");
        fieldMap.put("price_out", "商品售价");
        fieldMap.put("maker", "生产厂家");
        fieldMap.put("brand", "品牌");
        fieldMap.put("update_date", "最后修改时间");
        fieldMap.put("pic", "商品图片");
        //导出用户相关信息
        new ExportExcelUtils().export(excelName, goodsList, fieldMap, response);
    }

    @RequestMapping("/goods_in/excelDownload")
    public void goods_in_download(HttpServletResponse response, HttpServletRequest request) {

        //得到所有要导出的数据
        List<GoodsInList> goodsInLists = goodsInListService.queryGoodsInListList();

        //定义导出的excel名字
        String excelName = "商品进货单详情表";
        //获取需要转出的excel表头的map字段
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
        fieldMap.put("goods_in_list_id", "进货单编号");
        fieldMap.put("goods_id", "商品编号");
        fieldMap.put("price_in", "商品进价");
        fieldMap.put("num", "进货数量");
        fieldMap.put("do_who", "进货管理员账号");
        fieldMap.put("do_time", "进货时间");

        //导出相关信息
        new ExportExcelUtils().export(excelName, goodsInLists, fieldMap, response);
    }


    @RequestMapping("/admin_record/excelDownload")
    public void admin_record_download(HttpServletResponse response, HttpServletRequest request) {

        //得到所有要导出的数据
        List<AdminRecord> adminRecords = adminRecordService.queryRecord();

        //定义导出的excel名字
        String excelName = "管理员操作记录详情表";
        //获取需要转出的excel表头的map字段
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
        fieldMap.put("record_id", "记录编号");
        fieldMap.put("do_who", "操作者(账号)");
        fieldMap.put("do_role", "操作者角色");
        fieldMap.put("done_who", "操作对象(账号/编号)");
        fieldMap.put("done_role", "操作对象角色");
        fieldMap.put("do_what", "操作内容");
        fieldMap.put("do_time", "操作时间");

        //导出用户相关信息
        new ExportExcelUtils().export(excelName, adminRecords, fieldMap, response);
    }
    /*
    @RequestMapping(value="getImgBase64",method = RequestMethod.GET)
    public Object getImgBase64(@RequestParam("idFile")Long idFile){

        FileInfo fileInfo = fileService.get(idFile);
        FileInputStream fis = null;
        try {
            File file = new File(fileInfo.getAblatePath());
            byte[] bytes = new byte[(int) file.length()];
            fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            bis.read(bytes);
            String base64 = CryptUtil.encodeBASE64(bytes);
            return Rets.success(Maps.newHashMap("imgContent", base64));
        } catch (Exception e) {
            logger.error("get img error",e);
            return Rets.failure("获取图片异常");
        }finally{
            try {
                fis.close();
            }catch (Exception e){
                logger.error("close getImgBase64 error",e);
            }
        }

    }

     */

/*
    @RequestMapping(value="getImgStream",method = RequestMethod.GET)
    public void getImgStream(HttpServletResponse response,
                             @RequestParam("idFile")Long idFile){
        FileInfo fileInfo = fileService.get(idFile);
        FileInputStream fis = null;
        response.setContentType("image/"+fileInfo.getRealFileName().split("\\.")[1]);
        try {
            OutputStream out = response.getOutputStream();
            File file = new File(fileInfo.getAblatePath());
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            logger.error("getImgStream error",e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.error("close getImgStream error",e);
                }
            }
        }
    }

 */
}
